package com.jcwy.common;

import cn.hutool.json.JSONUtil;
import com.jcwy.common.dto.MsgDto;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.Type;
import java.util.Optional;

/**
 * MySql数据同步到其他
 *
 * @author yicol
 */
public interface IMysqlSyncPlugin<T> {


    /**
     * 表名
     *
     * @return
     */
    String tableName();

    /**
     * 获取泛型类型
     *
     * @return
     * @throws ClassNotFoundException
     */
    default Class<T> getClazz() throws ClassNotFoundException {
        Type[] genericInterfaces = getClass().getGenericInterfaces();
        ParameterizedTypeImpl genericInterface = (ParameterizedTypeImpl) genericInterfaces[0];
        Type actualTypeArgument = genericInterface.getActualTypeArguments()[0];
        return (Class<T>) Class.forName(actualTypeArgument.getTypeName());
    }

    /**
     * 处理数据
     *
     * @param message
     */
    default void process(MsgDto message) throws ClassNotFoundException {
        T t = JSONUtil.parseObj(message.getData()).toBean(getClazz());
//        List<T> dataList = JSONUtil.parseArray(message.getData()).toList(getClazz());
//        List<T> dataList = CollUtil.newArrayList(t);
        if (!Optional.ofNullable(t).isPresent()) {
            return;
        }
        switch (message.getOp()) { // INSERT UPDATE DELETE
            case "c":
                System.out.println("---------插入数据：" + JSONUtil.toJsonStr(t));
                insertEvent(message, t);
                break;
            case "u":
                System.out.println("---------更新数据：" + JSONUtil.toJsonStr(t));
                updateEvent(message, t);
                break;
            case "d":
                System.out.println("---------删除数据：" + JSONUtil.toJsonStr(t));
                deleteEvent(message, t);
                break;
            default:
                break;
        }
    }

    /**
     * 新增
     */
    void insertEvent(MsgDto message, T t);

    /**
     * 更新
     */
    void updateEvent(MsgDto message, T t);

    /**
     * 删除
     */
    void deleteEvent(MsgDto message, T t);

}
